﻿package cn.whdream.syn;

import java.util.Iterator;

public class SynDemo {
	
	public static void main(String[] args) throws InterruptedException {
		Web12306 web = new Web12306();
		Thread t1 = new Thread(web,"路人甲");
		Thread t2 = new Thread(web,"黄牛已");
		Thread t3 = new Thread(web,"攻城狮");
		t1.start();
		t2.start();
		t3.start();
	}
}
/**
 * 线程安全的类
 * @author Administrator
 *
 */
class Web12306 implements Runnable {
	private int num =10;
	private boolean flag =true;
	@Override
	public void run() {
		while(flag){
			test3();
		}
	}
	//线程不安全
		public  void test4() {
			//锁定当前对象
			synchronized (this) {
				if (num <= 0) {
					flag = false;
					return;
				}
			}	
				try {
					Thread.sleep(500);
				}catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
		
			
		}
	//线程安全
	public  void test3() {
		//锁定当前对象
		synchronized (this) {
			if (num <= 0) {
				flag = false;
				return;
			}
			try {
				Thread.sleep(500);
			}catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
		}
		
	}
	//锁定线程
	public synchronized void test2() {
		if (num <= 0) {
			flag = false;
			return;
		}
		try {
			Thread.sleep(500);
		}catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
	}
	//线程不安全
	public void test1(){
		if(num<=0){
			flag=false; //跳出循环
			return ;
		}
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()+"抢到了"+num--);
	}
}
